package com.dragon.mmochat.service;

import java.awt.Color;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dragon.mmochat.MmochatConstant;
import com.dragon.mmochat.MmochatMain;
import com.dragon.mmochat.model.MmochatRolePayInfo;
import com.dragon.mmochat.model.attackMode.MmochatAttackModeOfNormal;
import com.dragon.mmochat.model.attackMode.MmochatAttackModeOfRescueTeamer;
import com.dragon.mmochat.model.enumType.MmochatActivityRecordType;
import com.dragon.mmochat.model.enumType.MmochatBigMoneyEarnType;
import com.dragon.mmochat.model.enumType.MmochatBossLevelType;
import com.dragon.mmochat.model.enumType.MmochatNpcItemType;
import com.dragon.mmochat.model.enumType.MmochatRoleBmpType;
import com.dragon.mmochat.model.enumType.MmochatTaskType;
import com.dragon.mmochat.model.map.MmochatMap;
import com.dragon.mmochat.model.map.MmochatPoint;
import com.dragon.mmochat.model.role.MmochatMonsterFactory;
import com.dragon.mmochat.model.role.MmochatNpc;
import com.dragon.mmochat.model.role.MmochatPlayer;
import com.dragon.mmochat.model.role.MmochatRankPlayer;
import com.dragon.mmochat.model.role.MmochatTempNpc;
import com.dragon.mmochat.model.task.MmochatNpcBattle;
import com.dragon.mmochat.model.task.MmochatTask;
import com.dragon.mmochat.util.MmochatUtil;
import com.skymobi.message.widget.CreateMsgBoxTLV;
import com.skymobi.message.widget.CtrlTLVStructureRequest;
import com.skymobi.message.widget.SendDataTLV;
import com.skymobi.message.widget.ShowWaitingMsgBoxTLV;
import com.skymobi.util.Text;

//临时活动
public class MmochatTempActivityService {
	private static Logger log = LoggerFactory
			.getLogger(MmochatTempActivityService.class);

	/************************* 活动参数:程序手动设置 **************************/
	// 全民免费洗点时间；如果没有此活动，则设为空数组；格式："yyyy-MM-dd"
	public static String[] freePointDay = new String[] { "2013-02-09",
			"2013-02-10", "2013-02-11", "2013-02-12", "2013-02-13",
			"2013-02-14", "2013-02-15" };

	// 在线送K币活动
	public static ScheduledExecutorService activityThread = Executors
			.newScheduledThreadPool(1);

	// 年兽活动
	public static ScheduledExecutorService yearMonsterThread = Executors
			.newScheduledThreadPool(1);

	// 蛇年在线所有人送888元宝
	public static ScheduledExecutorService sendBigMoneyThread = Executors
			.newScheduledThreadPool(1);

	// 2月4号-2月6号期间每隔1小时更新一次充值排行榜
	public static ScheduledExecutorService payRankThread = Executors
			.newScheduledThreadPool(1);

	// 新服全民在线送K币
	// public static ScheduledExecutorService allOnlineKbThread = Executors
	// .newScheduledThreadPool(1);

	// 充值排行榜
	public static List<MmochatRolePayInfo> payRank = new ArrayList<MmochatRolePayInfo>();

	// 感恩节领取名单:roleId-->0
	public static Map<Integer, Byte> thanksGivingMap = new ConcurrentHashMap<Integer, Byte>();

	// 圣诞节领取名单:roleId->0
	public static Map<Integer, Byte> chrismasMap = new ConcurrentHashMap<Integer, Byte>();

	// 新年礼物领取名单:roleId->0
	public static Map<Integer, Byte> newYearMap = new ConcurrentHashMap<Integer, Byte>();

	@SuppressWarnings("deprecation")
	public void init() {
		// 在线送K币活动
		Date now = new Date();
		// int start = 60 - now.getMinutes(); // 1-60
		// activityThread.scheduleAtFixedRate(new OnlineSendKBActivity(), start,
		// 60, TimeUnit.MINUTES);

		yearMonsterThread.scheduleAtFixedRate(new YearMonsterActivity(), 1, 3,
				TimeUnit.MINUTES);

		// 所有在线送666元宝,2月10号0点0分0秒执行
		{
			Calendar firstDay = Calendar.getInstance();
			int year = firstDay.get(Calendar.YEAR);
			firstDay.set(year, 1, 10, 0, 0, 0);
			long tick = firstDay.getTimeInMillis();

			long rest = (tick - System.currentTimeMillis())
					/ MmochatConstant.MS_PER_SECOND;
			if (rest >= 0) {
				sendBigMoneyThread.schedule(new OnlineSendBigMoneyActivity(),
						rest, TimeUnit.SECONDS);
			}
		}

		// 充值排行榜
		// int start = 60 - now.getMinutes();
		// rankPay();
		// payRankThread.scheduleAtFixedRate(new payRankClass(), start, 60,
		// TimeUnit.MINUTES);

		// // 新服在线全民送K币活动
		// allOnlineKbThread.scheduleAtFixedRate(new AllOnlineSendKBActivity(),
		// 1,
		// 1, TimeUnit.MINUTES);
	}

	// 充值排行榜
	private static void rankPay() {
		Date now = new Date();
		if ((now.getMonth() == 1 && now.getDate() >= 4 && now.getDate() <= 6)
				|| (now.getMonth() == 1 && now.getDate() == 7
						&& now.getHours() == 0 && now.getMinutes() < 10)) {
			// 2月4号-2月6号期间每隔1小时更新一次
			// 2月7号0点10分前再更新最后一次
			List<MmochatRolePayInfo> payRankBak = MmochatDao.getTopPayList(10);
			List<MmochatRolePayInfo> oldRank = payRank;
			payRank = payRankBak;
			oldRank.clear();

			// 设置抽奖次数
			int index = 1;
			for (MmochatRolePayInfo info : payRank) {
				int initValue = 0;
				if (index == 1) {
					initValue = 1;
				} else if (index <= 4) {
					initValue = 3;
				} else if (index <= 7) {
					initValue = 2;
				} else if (index <= 10) {
					initValue = 1;
				}
				info.initAwardTimes(initValue);
				index++;
			}
		}
	}

	class payRankClass implements Runnable {
		@Override
		public void run() {
			try {
				rankPay();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	// 在线全民送K币活动
	class AllOnlineSendKBActivity implements Runnable {
		@SuppressWarnings("deprecation")
		@Override
		public void run() {
			try {
				if (!MmochatConstant.isAllOnlineSendKbOpen) {
					return;
				}

				// 活动时间:9月27、28
				Date now = new Date();
				if (now.getMonth() != 8) {
					return;
				}
				int day = now.getDate();
				if (day != 27 && day != 28) {
					return;
				}
				int hour = now.getHours();
				int min = now.getMinutes();
				if (day == 27) {
					// 开服当天
					if (hour < 18) {
						// 开服-17：59，3小时，每隔15分钟送一次, 所有在线玩家送1K币(3000人)
						if (min == 0 || min == 15 || min == 30 || min == 45) {
							Map<Integer, MmochatPlayer> players = new ConcurrentHashMap<Integer, MmochatPlayer>(
									MmochatMainService.players);
							String text = "";
							String msg = "恭喜您在"
									+ MmochatUtil.wrapColor("在线送K币",
											Color.yellow)
									+ "活动中获得1K币，K币将在国庆后统一发放。"
									+ MmochatUtil.wrapColor(
											"(活动期间所有在线玩家，只要等级达到要求，"
													+ "就会每隔一段时间收到系统赠送的K币，"
													+ "K币额度会随着活动的进行逐渐增加，"
													+ "详情见游戏公告)", Color.red);
							for (MmochatPlayer me : players.values()) {
								if (me != null) {
									text += me.getSkyId() + "|";
									MmochatGmService.sendKufuPrivateMsg(me
											.getRoleId(), msg, false);
								}
							}
							players.clear();
							try {
								MmochatDao.addNewActivityRecord(0, 0, 1,
										MmochatActivityRecordType.在线全民送1K币,
										text);
							} catch (Exception e) {
								e.printStackTrace();
							}
							String sysMsg = "恭喜当前"
									+ MmochatUtil.wrapColor("所有在线",
											Color.yellow) + "的玩家，每人获得1K币。"
									+ "至18:00前每隔15分钟发放一次K币。"
									+ "18点后只有10级以上在线玩家才能获得K币，K币也将更多。";
							MmochatChatService.sendSystemMsg(sysMsg);
						}
					} else if (hour < 23) {
						// 18：00-23：00，6小时，每隔30分钟送一次，10级以上玩家，送3K币(2000人)
						if (min == 0 || min == 30) {
							Map<Integer, MmochatPlayer> players = new ConcurrentHashMap<Integer, MmochatPlayer>(
									MmochatMainService.players);
							String text = "";
							String msg = "恭喜您在"
									+ MmochatUtil.wrapColor("在线送K币",
											Color.yellow)
									+ "活动中获得3K币，K币将在国庆后统一发放。"
									+ MmochatUtil.wrapColor(
											"(活动期间所有在线玩家，只要等级达到要求，"
													+ "就会每隔一段时间收到系统赠送的K币，"
													+ "K币额度会随着活动的进行逐渐增加，"
													+ "详情见游戏公告)", Color.red);
							for (MmochatPlayer me : players.values()) {
								if (me != null && me.getLevel() >= 10) {
									text += me.getSkyId() + "|";
									MmochatGmService.sendKufuPrivateMsg(me
											.getRoleId(), msg, false);
								}
							}
							players.clear();
							try {
								MmochatDao.addNewActivityRecord(0, 0, 1,
										MmochatActivityRecordType.在线全民送3K币,
										text);
							} catch (Exception e) {
								e.printStackTrace();
							}
							String sysMsg = "恭喜当前"
									+ MmochatUtil.wrapColor("所有在线的10级(以上)",
											Color.yellow) + "玩家，每人获得3K币。"
									+ "至22:59每隔30分钟对10级(以上)玩家发放一次K币。"
									+ "明天11:00开始继续送K币。";
							MmochatChatService.sendSystemMsg(sysMsg);
						}
					}
				} else if (day == 28) {
					// 开服第二天
					if (hour >= 11 && hour <= 17) {
						// 11：00-17：00，7小时，每隔1小时送一次，15级以上玩家，送5K币(2000人)
						if (min == 0) {
							Map<Integer, MmochatPlayer> players = new ConcurrentHashMap<Integer, MmochatPlayer>(
									MmochatMainService.players);
							String text = "";
							String msg = "恭喜您在"
									+ MmochatUtil.wrapColor("在线送K币",
											Color.yellow)
									+ "活动中获得5K币，K币将在国庆后统一发放。"
									+ MmochatUtil.wrapColor(
											"(活动期间所有在线玩家，只要等级达到要求，"
													+ "就会每隔一段时间收到系统赠送的K币，"
													+ "K币额度会随着活动的进行逐渐增加，"
													+ "详情见游戏公告)", Color.red);
							for (MmochatPlayer me : players.values()) {
								if (me != null && me.getLevel() >= 15) {
									text += me.getSkyId() + "|";
									MmochatGmService.sendKufuPrivateMsg(me
											.getRoleId(), msg, false);
								}
							}
							players.clear();
							try {
								MmochatDao.addNewActivityRecord(0, 0, 1,
										MmochatActivityRecordType.在线全民送5K币,
										text);
							} catch (Exception e) {
								e.printStackTrace();
							}
							String sysMsg = "恭喜当前"
									+ MmochatUtil.wrapColor("所有在线的15级(以上)",
											Color.yellow) + "玩家，每人获得5K币。"
									+ "至17:59每隔1小时对15级(以上)玩家发放一次K币。";
							MmochatChatService.sendSystemMsg(sysMsg);
						}
					} else if (hour >= 18 && hour <= 23) {
						// 18：00-23：00，6小时，每隔1小时送一次，30级以上玩家，送10K币(1000人)
						if (min == 0) {
							Map<Integer, MmochatPlayer> players = new ConcurrentHashMap<Integer, MmochatPlayer>(
									MmochatMainService.players);
							String text = "";
							String msg = "恭喜您在"
									+ MmochatUtil.wrapColor("在线送K币",
											Color.yellow)
									+ "活动中获得10K币，K币将在国庆后统一发放。"
									+ MmochatUtil.wrapColor(
											"(活动期间所有在线玩家，只要等级达到要求，"
													+ "就会每隔一段时间收到系统赠送的K币，"
													+ "K币额度会随着活动的进行逐渐增加，"
													+ "详情见游戏公告)", Color.red);
							for (MmochatPlayer me : players.values()) {
								if (me != null && me.getLevel() >= 30) {
									text += me.getSkyId() + "|";
									MmochatGmService.sendKufuPrivateMsg(me
											.getRoleId(), msg, false);
								}
							}
							players.clear();
							try {
								MmochatDao.addNewActivityRecord(0, 0, 1,
										MmochatActivityRecordType.在线全民送10K币,
										text);
							} catch (Exception e) {
								e.printStackTrace();
							}
							String sysMsg = "恭喜当前"
									+ MmochatUtil.wrapColor("所有在线的30级(以上)",
											Color.yellow) + "玩家，每人获得10K币。"
									+ "至23:00每隔1小时对30级(以上)玩家发放一次K币。";
							MmochatChatService.sendSystemMsg(sysMsg);
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	// 在线抽奖送K币活动
	class OnlineSendKBActivity implements Runnable {
		@SuppressWarnings("deprecation")
		@Override
		public void run() {
			try {
				Date now = new Date();
				if (now.getMonth() == 4
						&& (now.getDate() == 26 || now.getDate() == 27)) {
					int hour = now.getHours(); // 0-23
					if (hour >= 13 && hour <= 22) {
						List<MmochatPlayer> onlineList = new ArrayList<MmochatPlayer>(
								MmochatMainService.players.values());
						if (onlineList.size() > 0) {
							int index = MmochatUtil.getRandomValue(onlineList
									.size());
							MmochatPlayer me = onlineList.get(index);
							if (me != null) {
								try {
									MmochatDao
											.addNewActivityRecord(
													me.getSkyId(),
													me.getRoleId(),
													1000,
													MmochatActivityRecordType.五月末在线送1000K币,
													me.getName());
								} catch (Exception e) {
									e.printStackTrace();
									return;
								}
								String sysInfo = "恭喜"
										+ MmochatUtil.wrapColor(me.getName(),
												Color.green)
										+ "获得在线大奖"
										+ MmochatUtil.wrapColor("1000K币",
												Color.yellow)
										+ "。本周六、周日两天，13:00至22:00每小时抽取一名在线玩家获得K币大奖。";
								MmochatChatService.sendSystemMsg(sysInfo);
								String userInfo = "恭喜您获得"
										+ MmochatUtil.wrapColor("1000K币",
												Color.yellow)
										+ "在线大奖。本周六、周日两天，13:00至22:00每小时都会随机抽取一名"
										+ "在线玩家获得K币大奖。"
										+ MmochatUtil
												.wrapColor(
														"K币将在活动结束后7个工作日内统一发放，请关注平台短信通知。",
														Color.red);
								MmochatGmService.sendKufuPrivateMsg(me
										.getRoleId(), userInfo, false);
							}
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	// 年兽活动:每隔3分钟放一次怪，怪寿命3分钟
	class YearMonsterActivity implements Runnable {
		@SuppressWarnings("deprecation")
		@Override
		public void run() {
			try {
				Date now = new Date();
				if (now.getMonth() == 1
						&& (now.getDate() == 7 || now.getDate() == 8 || now
								.getDate() == 9)) {
					int hour = now.getHours(); // 0-23
					if (hour == 22) {
						// 放怪
						log.debug("发布年兽");
						Integer[] mapIds = new Integer[] { 2, 10, 11, 1, 16, 3,
								19, 20 };
						int mapIndex = MmochatUtil
								.getRandomValue(mapIds.length);
						int mapId = mapIds[mapIndex];
						MmochatPoint point = MmochatMapService
								.getRandReachablePoint(mapId);
						if (point != null) {
							MmochatTempNpc boss = new MmochatTempNpc(true);
							MmochatNpcService.npcs.put(boss.getNpcId(), boss);
							boss.setName("年兽");
							boss.getFunctionItems()
									.add(MmochatNpcItemType.驱赶年兽);
							boss.setLevel(30);
							boss.setLifeTime(180000);
							boss.setBmpType(MmochatRoleBmpType.怪物);
							boss.setMapId(mapId);
							short x = (short) (point.getX() * 24 + Math
									.random() * 24);
							short y = (short) (point.getY() * 24 + Math
									.random() * 24);
							boss.setX(x);
							boss.setY(y);
							MmochatMap theMap = MmochatMapService.maps
									.get(mapId);
							if (theMap == null) {
								return;
							}
							log.debug("年兽出现在" + theMap.getMapName() + "(" + x
									+ "," + y + ")");
							theMap.addNpc(boss);

							String context = MmochatUtil.wrapColor("年兽",
									Color.red)
									+ "出现在"
									+ MmochatUtil.wrapColor(theMap.getMapName()
											+ "(" + x + "," + y + ")",
											Color.cyan)
									+ "了，挑战成功可获得年兽蛋，有机率孵化出白娘子(变异)噢!(点击可自动寻路)";
							MmochatChatService.sendSystemMsg(context, theMap
									.getMapId(), x, y);
						}
					}

				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	// 在线所有人送元宝
	class OnlineSendBigMoneyActivity implements Runnable {
		@Override
		public void run() {
			try {
				List<MmochatPlayer> players = new ArrayList<MmochatPlayer>(
						MmochatMainService.players.values());
				int totalMoney = 0;
				for (MmochatPlayer me : players) {
					try {
						if (me != null) {
							if (me.getLevel() < 30) {
								continue;
							}
							// 标准道行
							int standDao = MmochatBattleService.getStandardDao(
									me.getLevel(), me.getLife_turn());
							double times = me.getDao() / Math.max(standDao, 1);// 0-10倍

							int money = (int) (100 * times + 100);
							totalMoney += money;
							me.addBig_money(money);
							String info = "蛇年到!仙剑问情感谢您陪伴我们"
									+ "度过了又一个春节，特奉上"
									+ MmochatUtil.wrapColor(money + "元宝",
											Color.magenta)
									+ "(元宝数=100+100X您的道行/标准道行,"
									+ "标准道行=等级的三次方X0.29/365(年))，祝您事事顺心，心想事成!";
							MmochatFriendService
									.sendSystemMsgToPersonByFriendMessage(me,
											info);
							MmochatChatService.sendSystemMsgToPerson(me,
									MmochatUtil.wrapColor(info, Color.yellow));
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				MmochatStatisticsService.addBigMoneyEarn(
						MmochatBigMoneyEarnType.在线送元宝, totalMoney);
				String sysInfo = "蛇年到!仙剑问情感谢您陪伴我们度过了又一个春节，"
						+ "我们为所有在线的30级以上用户送上一个元宝压岁钱!祝大家事事顺心，心想事成!";
				MmochatChatService.sendSystemMsg(sysInfo);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}
}
